﻿using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;

namespace CodeCounsel.SharePoint.RibbonDesigner.Model
{
    public class ResultDocumentBuilder
    {
        public static XStreamingElement GetResultDocument(DomainElement domainModel)
        {
            XStreamingElement result = null;
            DomainElement targetModel = GetReplacedModel(domainModel);
            if (targetModel != null)
            {
                result = new XStreamingElement(targetModel.DataModel.Name,
                    targetModel.DataModel.Attributes(),
                    targetModel.Children.Select( m => GetResultDocument(m)),
                    GetAppendedModels(targetModel).Select(m => GetResultDocument(m)));
            }
            return result;
        }

        private static IEnumerable<DomainElement> GetAppendedModels(DomainElement domainModel)
        {
            return domainModel.Extensions
                .Where(e => e.Type == CommandUIExtensionType.Append)
                .Select(e => e.Content);                
        }

        private static DomainElement GetReplacedModel(DomainElement domainModel)
        {
            CommandUIDefinition extension = domainModel.Extensions
                .Where(e => e.Type == CommandUIExtensionType.Replace)
                .FirstOrDefault();
            return extension != null ? extension.Content : domainModel;
        }
    }
}
